package org.jeecg.modules.hand;

import cn.hutool.core.util.ByteUtil;
import com.alibaba.fastjson.util.TypeUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.c.entity.MSC;

import org.jeecg.modules.c.service.IMSCService;
import org.jeecg.modules.enmu.AttributeLength;
import org.jeecg.modules.enmu.MessageTypeEnum;
import org.jeecg.modules.utils.SendMessageUtils;
import org.jeecg.modules.vo.Message;
import org.springframework.beans.BeansException;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


@Component
@Slf4j
public class LoginHandler extends ChannelInboundHandlerAdapter implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    public static Channel goladChannel;

    private static final AttributeKey<Integer> LOGGED_IN_KEY = AttributeKey.valueOf("isLoggedIn");

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    //   goladChannel = ctx.channel();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        // ctx.fireChannelRead(msg);
        Integer isLoggedIn = ctx.channel().attr(LOGGED_IN_KEY).get();
        if (isLoggedIn == null) {
            if (msg instanceof Message) {

                Message message = (Message) msg;
                int messageType = message.getMessageType();
                ByteBuf buffer = message.getBuffer();
                if (messageType != MessageTypeEnum.LOGIN.getValue()) {
                    // 非登录消息，拒绝处理
                    ctx.close();
                    return;
                }
                // 登录消息，处理登录逻辑
                //根据登录的用户名，获取当登录信息
                // 消息内容为固定格式,直接从第16个字节开始解析到第19个字节结束。
                byte[] username = new byte[AttributeLength.USER_LENGTH.getLength()];
                byte[] password = new byte[AttributeLength.PASSWORD_LEN.getLength()];
                buffer.readBytes(username);
                buffer.readBytes(password);

                String name = new String(username).trim();
                String pwd = new String(password).trim();
                pwd = pwd.trim();
                //   System.out.println("用户名：" + name + " 密码：" + pwd);
                QueryWrapper qw = new QueryWrapper();
                qw.eq("name", name);
                IMSCService imscService = applicationContext.getBean(IMSCService.class);
                MSC one = imscService.getOne(qw);
                if (one == null) {
                    //用户不存在
                    ctx.close();
                    return;
                }
                if (!one.getPassword().equals(pwd)) {
                    //密码错误
                    ctx.close();
                    return;
                }
                // 登录成功，设置已登录标志
                ctx.channel().attr(LOGGED_IN_KEY).set(TypeUtils.castToInt(one.getAuth()));
                //根据msc获取管道
                Channel channel = ctx.channel();
                if (channel != null) {
                    goladChannel = channel;
                    message = new Message();
                    //登录名称
                    message.setMessageType(MessageTypeEnum.LOGIN_ACK.getValue());
                    //登录序列号
                    message.setMessageSerialNo(SendMessageUtils.messageSerialNo);

                    ByteBuf writeBuf = Unpooled.buffer();
                    writeBuf.writeIntLE(TypeUtils.castToInt(one.getAuth()));
                    message.setBuffer(writeBuf);
                    //  message.setMessageContent(ByteUtil.intToBytes(1, ByteOrder.LITTLE_ENDIAN));
                    channel.writeAndFlush(message);
                    // 处理完登录逻辑后，继续处理其他消息
                    ctx.fireChannelRead(msg);
                }
            }

        } else {
            if (msg instanceof Message) {
                Message message = (Message) msg;
                MessageTypeEnum messageTypeEnum = MessageTypeEnum.fromValue((int) message.getMessageType());
                if (messageTypeEnum == MessageTypeEnum.LOGOUT) {
                    ctx.channel().attr(LOGGED_IN_KEY).set(null);

                    //返回登出ACK
                    Message writeMessage = new Message();
                    //登录名称
                    writeMessage.setMessageType(MessageTypeEnum.LOGIN_ACK.getValue());
                    ctx.channel().writeAndFlush(writeMessage);
                    // 处理完登出逻辑后，继续处理其他消息
                    ctx.fireChannelRead(msg);
                    log.info("用户登出确认");
                } else {
                    // 直接处理其他消息
                    ctx.fireChannelRead(msg);
                }


            }

        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (LoginHandler.applicationContext == null) {
            LoginHandler.applicationContext = applicationContext;
        }
    }
}
